package topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import constant.Constant;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.Host);
        connectionFactory.setPort(Constant.Port);
        connectionFactory.setUsername(Constant.userName);
        connectionFactory.setPassword(Constant.userName);
        connectionFactory.setVirtualHost(Constant.VirtualHost);
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();

        // 声明交换机
        channel.exchangeDeclare(Constant.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC,true);
        // 声明队列
        channel.queueDeclare(Constant.TOPIC_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constant.TOPIC_QUEUE2,true,false,false,null);
        // 绑定交换机
        channel.queueBind(Constant.TOPIC_QUEUE1,Constant.TOPIC_EXCHANGE,"*.a.*");
        channel.queueBind(Constant.TOPIC_QUEUE2,Constant.TOPIC_EXCHANGE,"*.*.b");
        channel.queueBind(Constant.TOPIC_QUEUE2,Constant.TOPIC_EXCHANGE,"c.#");
        // 发送消息
        String msg = "这是一条路由关系的消息,发送到a";
        channel.basicPublish(Constant.TOPIC_EXCHANGE,"b.a.plus",null,msg.getBytes());

        String msg1 = "这是一条路由关系的消息,发送到b";
        channel.basicPublish(Constant.TOPIC_EXCHANGE,"topic.a.b",null,msg1.getBytes());

        String msg2 = "这是一条路由关系的消息,发送到c";
        channel.basicPublish(Constant.TOPIC_EXCHANGE,"c.test.topic.b",null,msg2.getBytes());

        System.out.println("消息发送成功");

        channel.close();
        connection.close();
    }
}
